<script setup lang="ts">
import { onMounted, onUnmounted, Ref, ref, shallowRef, watch } from 'vue'
import * as monaco from 'monaco-editor'
import { getCodeSuggestions } from '@/api/code/codeCompletion';
import { showNotify } from 'vant';

const codeEditBox = ref<HTMLElement | null>(null);
const content = defineModel("content") as Ref<string>;
const options = ref({} as monaco.editor.IStandaloneEditorConstructionOptions);
const editor = shallowRef({} as monaco.editor.IStandaloneCodeEditor);
const loading = ref(false);
const isEditorReady = ref(false);

onMounted(() => {
    initEditor();
})

const initEditor = () => {
    // 配置Monaco编辑器选项
    monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
        noSemanticValidation: true,
        noSyntaxValidation: false
    })
    
    monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
        target: monaco.languages.typescript.ScriptTarget.ES2020,
        allowNonTsExtensions: true
    })
    
    // 设置编辑器选项
    options.value = {
        value: content.value,
        wordWrap: 'on',
        language: 'sql',
        theme: 'vs-dark',
        automaticLayout: true,
        fontSize: 14,
        lineNumbers: 'on',
        minimap: { enabled: true },
        scrollbar: {
            verticalScrollbarSize: 10,
            horizontalScrollbarSize: 10,
            useShadows: false,
        },
        suggest: {
            snippetsPreventQuickSuggestions: false,
            showWords: true,
            showKeywords: true
        },
        tabSize: 2,
        padding: { top: 10 }
    };
    
    // 创建编辑器实例
    if (codeEditBox.value != null) {
        try {
            editor.value = monaco.editor.create(codeEditBox.value, options.value);
            
            // 监听内容变化
            editor.value.onDidChangeModelContent(() => {
                const now = editor.value.getValue();
                content.value = now;
            });
            
            // 注册AI补全提供者
            registerAICompletion();
            
            isEditorReady.value = true;
        } catch (error) {
            console.error('初始化编辑器失败:', error);
            showNotify({
                type: 'danger',
                message: '初始化编辑器失败，请刷新重试',
                position: 'top',
            });
        }
    }
}

// 监听外部内容变化
watch(() => content.value, (newVal) => {
    if (isEditorReady.value && editor.value && editor.value.getValue() !== newVal) {
        editor.value.setValue(newVal);
    }
});

// 销毁编辑器
onUnmounted(() => {
    if (editor.value) {
        editor.value.dispose();
    }
});

// 注册AI补全
const registerAICompletion = () => {
    monaco.languages.registerCompletionItemProvider('sql', {
        triggerCharacters: [' ', '.', ',', '('],
        async provideCompletionItems(model, position) {
            loading.value = true;
            
            try {
                // 获取当前行代码
                const code = model.getLineContent(position.lineNumber);
                const wordPos = new monaco.Position(position.lineNumber, position.column);
                const wordInfo = model.getWordUntilPosition(wordPos);
                
                // 请求AI建议
                const suggestions = await fetchAISuggestions(code);
                
                // 返回补全建议
                return {
                    suggestions: suggestions.map((suggestion: { text: string }) => ({
                        label: suggestion.text,
                        kind: monaco.languages.CompletionItemKind.Function,
                        insertText: suggestion.text,
                        detail: 'AI 建议',
                        range: new monaco.Range(
                            position.lineNumber,
                            wordInfo.startColumn,
                            position.lineNumber,
                            wordInfo.endColumn
                        )
                    }))
                };
            } finally {
                loading.value = false;
            }
        }
    });
};

// 获取AI补全建议
const fetchAISuggestions = async (codeContent: string) => {
    try {
        const response = await getCodeSuggestions(codeContent);
        const data = await response;
        
        const dataList = data.substring(3, data.length - 3)
            .split('\n')
            .filter((item) => {
                return item.trim().length !== 0 && item.indexOf('sql') === -1
            });
            
        return dataList.map((c) => ({ label: c, text: c }));
    } catch (error) {
        console.error('获取AI建议失败:', error);
        return [];
    }
};
</script>

<template>
    <div class="monaco-editor-container">
        <div ref="codeEditBox" class="code-edit-box">
            <!-- 编辑器区域 -->
        </div>
        
        <!-- AI加载指示器 -->
        <div v-if="loading" class="ai-loading-indicator">
            <van-loading size="14" />
            <span>AI正在思考...</span>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.monaco-editor-container {
    position: relative;
    width: 100%;
    height: 100%;
    
    .code-edit-box {
        width: 100%;
        height: 100%;
    }
    
    .ai-loading-indicator {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 1000;
        background: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 4px 10px;
        border-radius: 4px;
        font-size: 12px;
        display: flex;
        align-items: center;
        gap: 6px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    }
}
</style>